const { src, dest, watch, series, parallel,task } = require('gulp');
const del = require('del');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const babel = require('gulp-babel');
const connect=require('gulp-connect');	//本地服务
// const imagemin = require('gulp-imagemin');
const minifyCSS = require('gulp-minify-css');
const goweb = require('./gulp/goweb')
const goless = require('./gulp/goless')
const goscss = require('./gulp/goscss')
const gocss = require('./gulp/gocss')


/*定义web服务器任务*/
const serve = parallel( function (cb){
    connect.server({
        root: 'dist/',
        livereload: true,
        port: 8002
    });
    cb();
});


function msg(cb, type) {
    console.log(type, '<<<=== 所有事件执行完毕 ===>>>');
    cb()
}

// 清除 dist 下的文件
function clear() {
    return del('dist/**/*')
	
}

// 复制 html 文件
function copyhtml() {
    return src('src/**/*.html').pipe(dest('dist/')).pipe(connect.reload());
}

//复制fonts
function copyfonts() {
    return src('src/fonts/').pipe(dest('dist/')).pipe(connect.reload());
}
//复制iconfont
function copyiconfonts() {
    return src('src/iconfont/').pipe(dest('dist/')).pipe(connect.reload());
}


// 压缩css
function minicss() {
    return src('dist/css/**/*.css')
        .pipe(minifyCSS())
        .pipe(dest('dist/css'))
		.pipe(connect.reload());
}

// babel解析
function babelc() {
    return src('src/**/*.js')
        .pipe(babel({ presets: ['@babel/env'] }))
		//转化为es5文件名和地址都不变
        .pipe(dest('dist/'))
		.pipe(connect.reload());	
}
// 压缩 js 并修改后缀名
function minijs() {
    return src('dist/**/*.js')
        .pipe(uglify())
        // 把源文件，改为`.mini.js` 移动到 dist
        // .pipe(rename({ extname: '.min.js' }))
        .pipe(dest('dist/'))
		.pipe(connect.reload());
}

// 压缩图片
const miniimg = function () {
    return src('src/img/**/*.jpg')
        .pipe(imagemin({ progressive: true }))
        .pipe(dest('dist/img'))
		.pipe(connect.reload());
}

// 自动监控热更新
function dev() {
    return watch('src/**/*',series(clear, copyhtml,parallel(series(goless,goscss,gocss, minicss),babelc)))
}
//开发环境
exports.start=series(clear, copyhtml,copyfonts,copyiconfonts,parallel(series(goless,goscss,gocss, minicss),babelc),parallel(dev,serve))


exports.miniimg = miniimg

exports.clear = clear
exports.babelc = babelc
exports.minijs = minijs

exports.goweb = goweb
exports.goless = goless
exports.goscss = goscss
exports.gocss = gocss
exports.minicss = minicss
exports.dev = dev
exports.serve = serve

// 打包项目
exports.build = series(clear, copyhtml ,copyfonts,copyiconfonts,parallel(series(goless,goscss,gocss, minicss), series(babelc, minijs)), msg)
exports.default = msg